package owl2vowl.parser.helper;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLEntity;
import org.semanticweb.owlapi.model.OWLOntology;

public class ComparisonHelper {
	private static final Logger logger = LogManager.getLogger(ComparisonHelper.class);

	public static boolean hasDifferentNameSpace(OWLEntity entity, OWLOntology ontology, String loadedIri) {
		return hasDifferentNameSpace(entity.getIRI().toString(), ontology, loadedIri);
	}

	public static boolean hasDifferentNameSpace(String elementIri, String ontologyIri) {
		String trimmedElementIri = removeTrailingHash(elementIri);
		String trimmedOntologyIri = removeTrailingHash(ontologyIri);
		if (trimmedElementIri.equals(trimmedOntologyIri)) {
			return false;
		} else {
			if (trimmedElementIri.contains("#")) {
				String lastSlashIndex = trimmedElementIri.split("#")[0];
				if (lastSlashIndex.equals(trimmedOntologyIri)) {
					return false;
				}
			}

			if (trimmedElementIri.contains("/") && !trimmedElementIri.endsWith("/")) {
				int lastSlashIndex1 = trimmedElementIri.lastIndexOf("/");
				int indexAfterSlash = lastSlashIndex1 + 1;
				String elementNamespaceWithoutLastPart = trimmedElementIri.substring(0, indexAfterSlash);
				if (elementNamespaceWithoutLastPart.equals(trimmedOntologyIri)) {
					return false;
				}
			}

			return true;
		}
	}

	public static boolean hasDifferentNameSpace(String elementNamespace, OWLOntology ontology, String loadedIri) {
		if (elementNamespace == null) {
			logger.info("Namespace check: Element has no namespace!");
			return false;
		} else {
			String ontologyIri;
			if (ontology.isAnonymous()) {
				ontologyIri = loadedIri;
			} else {
				ontologyIri = ((IRI) ontology.getOntologyID().getOntologyIRI().get()).toString();
			}

			return hasDifferentNameSpace(elementNamespace, ontologyIri);
		}
	}

	public static String extractBaseIRI(String iri) {
		if (iri.endsWith("#")) {
			return iri.substring(0, iri.lastIndexOf("#"));
		} else if (iri.contains("#")) {
			iri = iri.split("#")[0];
			return iri;
		} else {
			if (iri.endsWith("/")) {
				iri = iri.substring(0, iri.lastIndexOf("/"));
			}

			return iri.substring(0, iri.lastIndexOf("/"));
		}
	}

	private static String removeTrailingHash(String text) {
		return text.replaceAll("#$", "");
	}
}